<template>
  <el-form :model="queryParams" ref="queryForm" size="default" :inline="true">
    <el-form-item label="角色名称" prop="roleName">
      <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-perms="['system:role:add']"
          v-preventReClick
      >新增
      </el-button>
    </el-col>
  </el-row>


  <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="tableData"
      row-key="menuId"
  >
    <el-table-column prop="roleId" label="角色编号" :show-overflow-tooltip="true" width="160"></el-table-column>
    <el-table-column prop="roleName" label="角色名称" :show-overflow-tooltip="true" width="160"></el-table-column>
    <el-table-column prop="roleSort" label="排序" width="60"></el-table-column>
    <el-table-column prop="status" label="状态" width="80">
      <template #default="scope">
        <status-tag :status="scope.row.status"/>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" align="center" prop="createTime"/>
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template #default="scope">
        <template v-if="scope.row.roleId !== 1">
          <el-tooltip placement="top" content="修改">
            <el-button
                link
                icon="Edit"
                type="primary"
                v-perms="['system:role:edit']"
                @click="handleUpdate(scope.row)"/>
          </el-tooltip>
          <el-tooltip placement="top" content="删除">
            <el-button
                link
                icon="Delete"
                v-perms="['system:role:remove']"
                type="danger"
                @click="handleDelete(scope.row)"/>
          </el-tooltip>
        </template>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-if="total>0"
      v-model:current-page="queryParams.pageNum"
      :page-size="10"
      layout="total, prev, pager, next"
      :total="total"
      style="float: right"
  />

  <el-dialog :title="title" v-model="open" width="600px" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称"/>
      </el-form-item>
      <el-form-item label="排序" prop="roleSort">
        <el-input-number v-model="form.roleSort" controls-position="right" :min="0"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio value="0" size="large">正常</el-radio>
          <el-radio value="1" size="large">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
        <el-tree
            class="tree-border"
            :data="menuTreeData"
            show-checkbox
            ref="menu"
            node-key="menuId"
            :props="treeProps"
            :default-expand-all="menuExpand"
            :check-strictly="!form.menuCheckStrictly"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel" v-preventReClick>取 消</el-button>
      <el-button type="primary" @click="submitForm" v-perms="['system:role:add','system:role:edit']" v-preventReClick>确
        定
      </el-button>
    </template>
  </el-dialog>
</template>
<script>
import StatusTag from "@/components/StatusTag.vue";
import {RoleService} from "@/api/system/role.js";
import {MenuService} from "@/api/system/menu.js";

export default {
  name: "SystemUser",
  components: {StatusTag},
  data() {
    return {
      // 查询参数
      queryParams: {
        roleName: ''
      },
      // 遮罩层
      loading: true,
      // 表格树数据
      tableData: [],
      // 重新渲染表格状态
      refreshTable: true,
      // 总共页码
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        status: '0'
      },
      // 表单校验
      rules: {
        roleName: [
          {required: true, message: "角色名称不能为空", trigger: "blur"}
        ],
        roleSort: [
          {required: true, message: "角色顺序不能为空", trigger: "blur"}
        ]
      },
      // 菜单是否展开
      menuExpand: true,
      // 菜单是否全选
      menuNodeAll: false,
      // 树形菜单数据
      menuTreeData: [],
      // 树形参数
      treeProps: {
        children: 'children',
        label: 'menuName'
      }
    }
  },
  methods: {
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleSort: 0,
        status: "0",
        menuIds: [],
        menuCheckStrictly: true,
        remark: undefined
      };
      this.$refs.form.resetFields()
    },
    getList() {
      this.loading = true;
      RoleService.getRoleList(this.queryParams).then(resp => {
        this.tableData = resp.rows
        this.total = resp.total;
        this.loading = false;
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleAdd() {
      this.$refs.queryForm.resetFields();
      this.getTreeMenuData();
      this.title = '添加角色'
      this.open = true;
    },
    getTreeMenuData() {
      MenuService.GetMenuList().then(resp => {
        this.menuTreeData = resp.data
      })
    },
    handleCheckedTreeExpand(value) {
      let treeList = this.menuTreeData;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].menuId].expanded = value
      }
    },
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuTreeData : [])
    },
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = value ? true : false
    },
    getMenuAllCheckedKeys() {
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    cancel() {
      this.reset();
      this.open = false;
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.roleId !== undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            const {code} = await RoleService.updateRole(this.form);
            if (code === 200) {
              this.$message.success('修改成功');
              this.open = false;
              this.getList();
            }
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            const {code} = await RoleService.addRole(this.form);
            if (code === 200) {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            }
          }
        }
      })
    },
    getRoleMenuTreeSelect(roleId) {
      return MenuService.GetRoleMenuTreeSelect(roleId).then(resp => {
        return resp
      })
    },
    handleUpdate(row) {
      const roleId = row.roleId;
      this.getTreeMenuData();
      const roleMenu = this.getRoleMenuTreeSelect(roleId);
      RoleService.getRole(roleId).then(resp => {
        this.form = resp.data;
        this.open = true;
        this.$nextTick(() => {
          roleMenu.then(res => {
            let checkedKeys = res.checkedKeys;
            this.$nextTick(() => {
              this.$refs.menu.setCheckedKeys(checkedKeys, true)
            })
          })
        })
        this.title = '修改角色'
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let _ = this;
      const roleId = row.roleId;
      _.$confirm('是否确认删除角色编号为"' + roleId + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        RoleService.deleteRole(roleId).then(resp => {
          if (resp.code === 200) {
            _.$message.success('删除成功');
            _.getList();
          }
        })
      }).catch(() => {
      });
    },
  },
  created() {
    this.getList();
  }
}
</script>
<style scoped>
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
  width: 100%;
  max-height: 266px;
  overflow-y: auto;
}
</style>
